//
//  AppUtils.m
//  habit
//
//  Created by huck on 15-9-1.
//  Copyright (c) 2015年 custom. All rights reserved.
//

#import "AppUtils.h"
#import "CommonCrypto/CommonDigest.h"
#import "UIImageView+WebCache.h"
#import "AppDelegate.h"
#import "BaseViewController.h"
#import "UpgradeView.h"
#import "DDMenuController.h"
#import "UserInfoViewController.h"
#import "ImagePickerViewController.h"


@implementation AppUtils

+ (LoginDataItem *)loginUser
{
    return [ServerMng sharedServerMng].loginUser;
}

+(BOOL)isLogin
{
    return LOGIN_USER!=nil && [AppUtils isNotEmpty: LOGIN_USER.userName] && [AppUtils isNotEmpty:LOGIN_USER.password];
}


+ (BOOL)isLogout
{
    return LOGIN_USER==nil || [AppUtils isEmpty: LOGIN_USER.userName] || [AppUtils isEmpty:LOGIN_USER.password];
}

+ (UserInfoViewController *)getLeftViewController;
{
  return [AppUtils getAppDelegate].leftViewController;
}

+ (DDMenuController *)getDDMenuViewController
{
    return [AppUtils getAppDelegate].ddMenu;
}

+ (void)showLeftViewController:(BOOL)show
{
    [[AppUtils getDDMenuViewController] showLeftController:YES show:show];
}

+ (MainViewController *)getmainViewController
{
    return  [AppUtils getAppDelegate].mainViewController;
}

+ (BaseNavigationController *)getRootNavigationController
{
    return  [AppUtils getAppDelegate].rootNav;
}

+ (AppDelegate *)getAppDelegate
{
   return (AppDelegate*)([UIApplication sharedApplication].delegate);
}

+ (UIViewController *)currentViewController
{
    UINavigationController *navigationController = [AppUtils getNavigationController];
    UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
    return lastViewController;
}

+ (UIView *)currentView
{
    return [AppUtils currentViewController].view;
}

+ (UINavigationController *)getNavigationController
{
    AppDelegate *delegate = [AppUtils getAppDelegate];
    return (UINavigationController *)delegate.rootNav;
}

+ (NSString *)currentVersion
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}

+ (NSInteger)currentBuildVersion
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [self toInteger: [infoDictionary objectForKey:@"CFBundleVersion"]];
}

+ (BOOL)isEmojiInputMode
{
    return [[[UIApplication sharedApplication] textInputMode].primaryLanguage isEqualToString:@"emoji"];
}

+ (NSString *)disableEmoji:(NSString *)text;
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@""];
    return modifiedString;
}

+ (BOOL)isEmpty:(NSString *)value
{
    return value == nil || [value isKindOfClass:[NSNull class]] || [AppUtils trim:value].length == 0;
}

+ (BOOL)isNotEmpty:(NSString *)value
{
    return ![AppUtils isEmpty:value];
}

+ (BOOL)isEmptyArray:(NSArray *)values
{
    return values == nil || values.count == 0;
}

+ (BOOL)isNotEmptyArray:(NSArray *)values
{
    return ![self isEmptyArray:values];
}

+ (BOOL)isNumeric:(NSString *)value
{
    if ([AppUtils isEmpty:value]) {
        return NO;
    }
    unichar ch;
    for (int i = 0; i < [value length]; i++) {
        ch = [value characterAtIndex:i];
        if (!isdigit(ch)) {
            return NO;
        }
    }
    return YES;
}

+ (BOOL)isPhoneNumber:(NSString *)value
{
    NSString *pattern = @"^1+[3578]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [pred evaluateWithObject:value];
    return  isMatch;
}

+ (BOOL)checkNum:(NSString *)value maxLen:(NSUInteger)len afterPointMax:(NSUInteger)after
{
    if ([AppUtils isEmpty:value] || value.length>len) {
        return NO;
    }
    if(after==0){
        return [AppUtils isNumeric:value];
    }
    NSString *regex = [NSString stringWithFormat:@"^[0-9]+(.[0-9]{0,%zi})?$",after];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:value];
    if (isMatch) {
        NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        int i = 0;
        while (i < value.length) {
            NSString * string = [value substringWithRange:NSMakeRange(i, 1)];
            NSRange range = [string rangeOfCharacterFromSet:tmpSet];
            if (range.length == 0) {
                return NO;
            }
            i++;
        }
    }
    return isMatch;
}

+ (BOOL)isAlpha:(NSString *)value
{
    if (value == nil) {
        return NO;
    }
    unichar ch;
    for (int i = 0; i < [value length]; i++) {
        ch = [value characterAtIndex:i];
        if (!isalpha(ch)) {
            return NO;
        }
    }
    return YES;
}

+ (BOOL)isWeakPassword:(NSString *)value
{
    if (value == nil) {
        return YES;
    }
    value = [AppUtils trim:value];
    if ([value length] < 6) {
        return YES;
    }
    if ([value length] >= 8) {
        return NO;
    }
    if ([AppUtils isNumeric:value] || [AppUtils isAlpha:value]) {
        return YES;
    }
    return NO;
}

+ (BOOL)equals:(NSString *)string another:(NSString *)another
{
    if (string == nil && another == nil) {
        return YES;
    }
    if (string == nil || another == nil) {
        return NO;
    }
    return [string isEqualToString:another];
}

+ (NSString *)trim:(NSString *)value
{
    if (value == nil) {
        return nil;
    }
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return [value stringByReplacingOccurrencesOfString:@"\u2006" withString:@""];
}

+ (NSString *)cutString:(NSString *)value len:(NSInteger)len
{
    if (value == nil) {
        return nil;
    }
    NSInteger strLen = value.length;
    if (strLen <= len) {
        return value;
    }
    return [value substringToIndex:len];
}

+ (NSString *)md5:(NSString *)value
{
    if ([self isEmpty:value]) {
        return nil;
    }
    const char *val = value.UTF8String;
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(val, (CC_LONG)strlen(val), outputBuffer);
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [outputString appendFormat:@"%02x",outputBuffer[i]];
    }
    
    return outputString.uppercaseString;
}

+ (NSUInteger)length:(NSString *)value
{
    if ([AppUtils isEmpty:value]) {
        return 0;
    }
    int i,n = [value length],l = 0,a = 0,b = 0;
    unichar c;
    for(i = 0; i < n; i++){
        c = [value characterAtIndex:i];
        if(isblank(c)){
            b++;
        } else if (isascii(c)) {
            a++;
        } else {
            l++;
        }
    }
    if (a == 0 && l == 0) {
        return 0;
    }
    return l + (int)ceilf((float)(a + b) / 2.0);
}

+ (NSUInteger)lengthCharacter:(NSString *)value
{
    if ([AppUtils isEmpty:value]) {
        return 0;
    }
    int i,n = [value length],l = 0,a = 0,b = 0;
    unichar c;
    for(i = 0; i < n; i++){
        c = [value characterAtIndex:i];
        if(isblank(c)){
            b++;
        } else if (isascii(c)) {
            a++;
        } else {
            l++;
        }
    }
    if (a == 0 && l == 0) {
        return 0;
    }
    return l*2 + a + b;
}

+ (NSString *)encodeURL:(NSString *)value
{
    if (value == nil) {
        return @"";
    }
    NSMutableString *temp = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%@", value]];
    NSString *resultStr = value;
    CFStringRef originalString = (__bridge CFStringRef) temp;
    CFStringRef leaveUnescaped = CFSTR(" ");
    CFStringRef forceEscaped = CFSTR("!'();:@&=+$,/?%#[]~");
    CFStringRef escapedStr;
    escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                         originalString,
                                                         leaveUnescaped,
                                                         forceEscaped,
                                                         kCFStringEncodingUTF8);
    if (escapedStr) {
        NSMutableString *mutableStr = [NSMutableString stringWithString:(__bridge NSString *)escapedStr];
        CFRelease(escapedStr);
        if (!mutableStr || [mutableStr isKindOfClass:[NSNull class]] || mutableStr.length <= 0) {
            return resultStr;
        }
        // replace spaces with plusses
        [mutableStr replaceOccurrencesOfString:@" "
                                    withString:@"+"
                                       options:0
                                         range:NSMakeRange(0, [mutableStr length])];
        resultStr = mutableStr;
    }
    return resultStr;
    //    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)value, NULL, (CFStringRef)@":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`", kCFStringEncodingUTF8));
    //    NSMutableString *output = [NSMutableString string];
    //    const unsigned char *source = (const unsigned char *)[value UTF8String];
    //    int sourceLen = strlen((const char *)source);
    //    for (int i = 0; i < sourceLen; ++i) {
    //        const unsigned char thisChar = source[i];
    //        if (thisChar == ' '){
    //            [output appendString:@"+"];
    //        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
    //                   (thisChar >= 'a' && thisChar <= 'z') ||
    //                   (thisChar >= 'A' && thisChar <= 'Z') ||
    //                   (thisChar >= '0' && thisChar <= '9')) {
    //            [output appendFormat:@"%c", thisChar];
    //        } else {
    //            [output appendFormat:@"%%%02X", thisChar];
    //        }
    //    }
    //    return output;
}

+ (NSString *)decodeURL:(NSString *)value
{
    if ([self isEmpty:value]) {
        return nil;
    }
    NSMutableString *outputStr = [NSMutableString stringWithString:value];
    [outputStr replaceOccurrencesOfString:@"+" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, outputStr.length)];
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

+ (NSString *)urlParam:(NSString *)url withKey:(NSString *)key
{
    if ([AppUtils isEmpty:url] || [AppUtils isEmpty:key]) {
        return @"";
    }
    NSError *error;
    NSString *reg = [NSString stringWithFormat:@"(%@=)([^#,&]+)", key];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:reg options:NSRegularExpressionCaseInsensitive error:&error];
    if (nil == regex) {
        return @"";
    }
    NSArray *matches = [regex matchesInString:url options:0 range:NSMakeRange(0, [url length])];
    if ([AppUtils isEmptyArray:matches]) {
        return @"";
    }
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];
        return tagValue;
    }
    return @"";
}

+ (id)parseJSON:(NSString *)value
{
    id object = nil;
    @try {
        NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
        object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    }
    @catch (NSException *exception) {
        DSLog(@"%s [Line %d] JSON字符串转成对象出错，原因：%@",  __PRETTY_FUNCTION__, __LINE__, exception);
    }
    return object;
}

+ (NSString *)toJSONString:(id)object
{
    NSString *jsonStr = @"";
    @try {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:0 error:nil];
        jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    @catch (NSException *exception) {
        DSLog(@"%s [Line %d] 对象转成JSON字符串出错，原因：%@", __PRETTY_FUNCTION__, __LINE__, exception);
    }
    return jsonStr;
}

+ (NSString *)getUUID
{
    NSString *uuid = [[NSUUID UUID] UUIDString];
    uuid = [uuid stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return [uuid lowercaseString];
}

+ (BOOL)hasConnected
{
    return [self hasConnected:NO];
}

+ (BOOL)hasConnected:(BOOL)showErrorMsg
{
    BOOL networkEnable = [ServerMng sharedServerMng].networkEnabled;
    if (!networkEnable && showErrorMsg) {
        [Toast makeText:@"没有网络连接，请连接网络" duration:ToastDurationLong];
    }
    return networkEnable;
}

+ (NetType)getNetWorkType
{
   return [ServerMng sharedServerMng].netType;
}

+ (void)popController:(UIViewController *)targetControllre{
    UINavigationController *nav = targetControllre.navigationController;
    NSMutableArray *viewControllers = [nav.viewControllers mutableCopy];
    NSMutableArray *newViewControllers=[[NSMutableArray alloc]init];
    Class cls = [targetControllre class];
    UIViewController *controller = nil;
    for (int i = 0; i < viewControllers.count; i++) {
        controller = [viewControllers objectAtIndex:i];
        if ([controller isKindOfClass:cls]) {
            [((BaseViewController *)controller) destory];
        }else{
            [newViewControllers addObject:controller];
        }
    }
    [nav setViewControllers:newViewControllers animated:YES];
}

//--------------------------------------------------
+ (void)jump:(UIViewController *)from to:(UIViewController *)to selectedIndex:(NSUInteger)selectedIndex
{
    NSMutableArray *viewControllers = [from.navigationController.viewControllers mutableCopy];
    Class cls = [BaseViewController class];
    UIViewController *controller = nil;
    for (int i = 1; i < viewControllers.count; i++) {
        controller = [viewControllers objectAtIndex:i];
        if ([controller isKindOfClass:cls]) {
            [((BaseViewController *)controller) destory];
        }
    }
    [viewControllers removeObjectsInRange:NSMakeRange(1, viewControllers.count - 1)];
    [viewControllers addObject:to];
    if (selectedIndex != -1) {
//        NSObject *obj = [viewControllers firstObject];
//        if ([obj isKindOfClass:[MainViewController class]]) {
//            MainViewController *mainController = (MainViewController *)obj;
//            mainController.selectedIndex = selectedIndex;
//        }
    }
    [from.navigationController setViewControllers:viewControllers animated:YES];
}

+ (void)jump:(UINavigationController *)navigation to:(UIViewController *)to after:(Class)after selectedIndex:(NSUInteger)selectedIndex
{
    NSMutableArray *viewControllers = [navigation.viewControllers mutableCopy];
    Class cls = [BaseViewController class];
    UIViewController *controller = nil;
    BOOL find = NO;
    NSUInteger index = viewControllers.count;
    for (int i = 0; i < viewControllers.count; i++) {
        controller = [viewControllers objectAtIndex:i];
        if(!find){
            if([controller isKindOfClass:after]){
                index = i+1;
                find = YES;
            }
            continue;
        }
        if ([controller isKindOfClass:cls]) {
            [((BaseViewController *)controller) destory];
        }
    }
    if(index<viewControllers.count){
        viewControllers = [[NSMutableArray alloc]initWithArray: [viewControllers subarrayWithRange:NSMakeRange(0,index)]];
    }
    [viewControllers addObject:to];
    if (selectedIndex != -1) {
//        NSObject *obj = [viewControllers firstObject];
//        if ([obj isKindOfClass:[MainViewController class]]) {
//            MainViewController *mainController = (MainViewController *)obj;
//            mainController.selectedIndex = selectedIndex;
//        }
    }
    [navigation setViewControllers:viewControllers animated:YES];
}

+ (void)backtoController:(Class)to;
{
   UINavigationController *nav = [AppUtils getNavigationController];
    NSArray *controllers = nav.viewControllers;
    NSInteger count = controllers.count;
    UIViewController *controller = nil;
    for (NSInteger i = count - 1; i >= 0; i--) {
        controller = controllers[i];
        if ([controller isKindOfClass:to]) {
            [nav popToViewController:controller animated:YES];
        }
    }
}

+ (UIViewController *)findBackForController:(Class)target;
{
    NSArray *controllers = [AppUtils getNavigationController].viewControllers;
    NSInteger count = controllers.count;
    UIViewController *controller = nil;
    for (NSInteger i = count - 1; i >= 0; i--) {
        controller = controllers[i];
        if ([controller isKindOfClass:target]) {
            return controller;
        }
    }
    return nil;
}

+ (void)setBackButtonStyle:(UIViewController *)controller
{
    controller.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:nil action:nil];
}

+ (void)centerButtonContent:(UIButton *)button spacing:(int)spacing
{
    CGSize imageSize = button.imageView.frame.size;
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, -(imageSize.height + spacing), 0);
    
    CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:button.titleLabel.font}];
    button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0, 0, -titleSize.width);
}

+ (UITextField *)getSearchBarTextField:(UISearchBar *)searchBar
{
    UITextField *textField = nil;

    UIView *viewTop = IS_IOS7H ? searchBar.subviews[0] : searchBar;
    for (UIView *subView in viewTop.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            
            [subView removeFromSuperview];
        }else if ([subView isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
            textField = (UITextField*)subView;
        }
    }
    return textField;
}

+ (UIButton *)setSearchBarButtonStyle:(UISearchBar *)searchBar
{
    UIView *viewTop = IS_IOS7H ? searchBar.subviews[0] : searchBar;
    NSString *classString = IS_IOS7H ? @"UINavigationButton" : @"UIButton";
    UIButton *button = nil;
    for (UIView *subView in viewTop.subviews) {
        if ([subView isKindOfClass:NSClassFromString(classString)]) {
            button = (UIButton*)subView;
            break;
        }
    }
    searchBar.tintColor = [UIColor colorWithString:COLOR_999999];
    searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    if (button) {
        [button setTitle:@"取消" forState:UIControlStateNormal];
        [button titleLabel].font = [UIFont systemFontOfSize:15];
    }
    return button;
}

+(void)setTableViewCellSelectBg:(UITableViewCell*)cell
{
    [AppUtils setTableViewCellSelectBg:cell color:nil];
}

+(void)setTableViewCellSelectBg:(UITableViewCell*)cell color:(UIColor*)color
{
    UIView *bgView = [[UIView alloc] init];

    if(color==nil){
        bgView.backgroundColor = [UIColor colorWithString:COLOR_DCDCDC];
        
    }else{
        bgView.backgroundColor = color;
    }
    cell.selectedBackgroundView = bgView;
}

+ (void)setCustomTitleView:(NSString *)title
{
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.frame =  CGRectMake(45, 0, SCREEN_WIDTH-2*45, 44);
    titleLabel.textColor = [UIColor colorWithString:COLOR_FFFFFF];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.text = title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [titleLabel sizeToFit];
    [AppUtils getNavigationController].viewControllers.lastObject.navigationItem.titleView = titleLabel;
}


+ (UITableViewCell *)getEmptyTableCell:(NSString *)message color:(UIColor *)color
{
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.frame = CGRectMake(0, 0, SCREEN_WIDTH, 103);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (color) {
        cell.backgroundColor = color;
    }
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,0,cell.frame.size.width-20, cell.frame.size.height) ];
    messageLabel.text = message;
    messageLabel.font = [UIFont boldSystemFontOfSize:15];
    messageLabel.textColor = [UIColor colorWithString:COLOR_999999];
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.backgroundColor = [UIColor clearColor];
    messageLabel.numberOfLines = 0;
    [cell addSubview:messageLabel];
    return cell;
}
+ (UITableViewCell *)getEmptyTableCell:(NSString *)message color:(UIColor *)color inCenter:(BOOL)isCenter
{
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.frame = CGRectMake(0, 0, SCREEN_WIDTH, CONTENT_HEIGHT-140);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (color) {
        cell.backgroundColor = color;
    }
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,0,cell.frame.size.width-20, cell.frame.size.height) ];
    messageLabel.text = message;
    messageLabel.font = [UIFont boldSystemFontOfSize:15];
    messageLabel.textColor = [UIColor colorWithString:COLOR_999999];
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.backgroundColor = [UIColor clearColor];
    messageLabel.numberOfLines = 0;
    [cell addSubview:messageLabel];
    return cell;
}


+ (UITableViewCell *)getEmptyTableCell:(NSString *)message
{
    return [AppUtils getEmptyTableCell:message color:nil];
}

+ (void)setSearchNoResult:(UISearchDisplayController *)controller message:(NSString *)message
{
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.001);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        UITableView *tableView = controller.searchResultsTableView;
        //only ios7,by songcf
        //tableView.separatorInset = UIEdgeInsetsZero;
        //end by songcf
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        for (UIView *subview in tableView.subviews) {
            if ([subview isKindOfClass: [UILabel class]]) {
                UILabel *targetLabel = (UILabel *)subview;
                if ([targetLabel.text isEqualToString:@"No Results"] || [targetLabel.text isEqualToString:@"无结果"]) {
                    targetLabel.text = message ? message : @"暂无搜索结果";
                    targetLabel.font = [UIFont systemFontOfSize:14];
                    targetLabel.textColor = [UIColor colorWithString:COLOR_999999];
                }
                break;
            }
        }
    });
}

+ (CALayer *)addSeparatorLine:(UIView *)view frame:(CGRect)frame
{
   return [AppUtils addSeparatorLine:view frame:frame color:nil];
}

+ (CALayer *)addSeparatorLine:(UIView *)view frame:(CGRect)frame color:(UIColor *)color
{
    CALayer *separator = [[CALayer alloc] init];
    separator.frame = frame;
    UIColor *borderColor = color ? color : [UIColor colorWithString:COLOR_E6E6E6];
    separator.borderColor = borderColor.CGColor;
    separator.borderWidth = frame.size.height;
    [view.layer addSublayer:separator];
    return separator;
}

+ (NSString *)toString:(id)value
{
    if (!value) {
        return @"";
    }
    return [NSString stringWithFormat:@"%@", value];
}

+ (NSString *)toString:(id)value replaceValue:(NSString *)replaceValue
{
    if ([AppUtils isEmpty:value]) {
        return replaceValue;
    }
    return [NSString stringWithFormat:@"%@", value];
}

+ (NSString *)toStr:(NSInteger)value
{
    return [NSString stringWithFormat:@"%zi", value];
}

+ (NSInteger)toInteger:(id)value
{
    return [[AppUtils toString:value] integerValue];
}

+ (NSInteger)randomInt:(NSUInteger)range offset:(NSInteger)offset
{
    return  (NSInteger)(arc4random() % range) + offset;
}

+ (NSInteger)randomInt:(NSUInteger)range
{
   return [AppUtils randomInt:range offset:0];
}

+ (NSString *)toHexString:(NSData *)value
{
    if (value == nil || value.length == 0) {
        return nil;
    }
    Byte *bytes = (Byte *)[value bytes];
    NSString *hexStr = @"";
    NSUInteger length = value.length;
    NSString *newHexStr = nil;
    for (int i = 0; i < length; i++) {
        newHexStr = [NSString stringWithFormat:@"%x", bytes[i] &0xff];
        if (newHexStr.length == 1) {
            hexStr = [NSString stringWithFormat:@"%@0%@", hexStr, newHexStr];
        } else {
            hexStr = [NSString stringWithFormat:@"%@%@", hexStr, newHexStr];
        }
    }
    return hexStr;
    
}
+ (NSData *)stringToHexData:(NSString *)string { //
    
    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}

+ (NSString *)getQueryString:(NSString *)url paramName:(NSString *)paramName
{
    NSError *error;
    NSString *pattern = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", paramName];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regex matchesInString:url options:NSMatchingReportCompletion range:NSMakeRange(0, url.length)];
    for (NSTextCheckingResult *match in matches) {
        return [url substringWithRange:[match rangeAtIndex:2]];
    }
    return nil;
}

+ (void)dispatchAsync:(void (^)(id))handle complection:(void (^)(id))completion object:(id)object
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        // 处理异步业务
        handle(object);
        // 异步执行完后，回到主线程执行操作
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(object);
        });
    });
}

+ (void)delay:(void (^)(void))completion delayTime:(NSTimeInterval)delayTime
{
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delayTime * NSEC_PER_SEC);
    dispatch_after(time, dispatch_get_main_queue(), completion);
}

+ (void)delay:(void (^)(void))completion
{
    [AppUtils delay:completion delayTime:0.2];
}

+ (void)showViewBorder:(UIView *)view
{
    view.layer.borderColor = [UIColor colorWithString:COLOR_D5392E].CGColor;
    view.layer.borderWidth = 1;
}

+ (BOOL)isScrollToTop:(UIScrollView *)scrollView
{
    if(scrollView.contentOffset.y <= 1) {
        return YES;
    }
    return NO;
}

+ (BOOL)isScrollToBottom:(UIScrollView *)scrollView
{
    float y = scrollView.contentOffset.y + scrollView.bounds.size.height;
    if(y > scrollView.contentSize.height - 20) {
        return YES;
    }
    return NO;
}

+ (void)showNetworkActivityIndicator
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

+ (void)hideNetworkActivityIndicator
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

+ (void)invalidateTimer:(NSTimer *)timer
{
    if (timer != nil) {
        [timer invalidate];
        timer = nil;
    }
}

+ (void)addObserver:(id)observer selector:(SEL)selector name:(NSString *)name
{
    [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:nil];
}

+ (void)removeObserver:(id)observer name:(NSString *)name
{
    [[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:nil];
}

+ (void)postNotificationName:(NSString *)name
{
    [self postNotificationName:name object:nil];
}

+ (void)postNotificationName:(NSString *)name object:(id)object
{
    [[NSNotificationCenter defaultCenter] postNotificationName:name object:object];
}

+ (void)postNotificationName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:name object:object userInfo:userInfo];
}

+ (NSString *)getClassName:(id)object
{
    return NSStringFromClass([object class]);
}

+(NSArray *) SplitStringToArray:(NSString *)strText separator:(NSString *)strSeparator
{
    NSArray  *   pItemsArray = nil;
    
    if(strText.length > 0 && strSeparator.length > 0)
    {
        pItemsArray = [strText componentsSeparatedByString:strSeparator];
    }
    else
    {
        pItemsArray = [NSArray arrayWithObject:strText];
    }
    
    return pItemsArray;
}


+ (UIView *)ShowWaitView:(UIView *) pParentView wait:(BOOL)bWait
{
    if(pParentView && bWait)
    {
        CGRect frame = pParentView.bounds;
        UIActivityIndicatorView * maskView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        
        maskView.backgroundColor = [UIColor clearColor];
        maskView.frame = frame;
        
        [pParentView addSubview:maskView];
        [pParentView bringSubviewToFront:maskView];
        
        return maskView;
    }
    
    return nil;
}


+ (void)HideWaitView:(UIView *) pWaitView
{
    if(pWaitView)
    {
        [pWaitView removeFromSuperview];
    }
}

+ (NSArray *)sortArray:(NSArray *) array descriptor:(NSString*)descriptor ascending:(BOOL)ascending
{
    if([AppUtils isEmptyArray:array]){
        return array;
    }
    NSSortDescriptor *fistDescriptor = [[NSSortDescriptor alloc] initWithKey:descriptor ascending:ascending];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:fistDescriptor,nil];
    
    return [array sortedArrayUsingDescriptors:sortDescriptors];
}

+ (NSMutableArray *)move:(NSArray *) array sourceIndex:(NSUInteger)sourceIndex destIndex:(NSUInteger)destIndex
{
    if([AppUtils isEmptyArray:array]){
        return nil;
    }
    NSMutableArray *result = [NSMutableArray arrayWithArray:array];
    sourceIndex = MIN(sourceIndex, array.count-1);
    destIndex = MIN(destIndex, array.count-1);

    id object = array[sourceIndex];
    [result removeObjectAtIndex:sourceIndex];
    [result insertObject:object atIndex:destIndex];
    
    return result;
}

+ (id)mutableContainer:(id)container
{
    if ([container isKindOfClass:[NSMutableArray class]]) {
        NSMutableArray *ret = [NSMutableArray arrayWithArray:container];
        for (NSInteger i = 0; i < ret.count; ++i) {
            id obj = [ret objectAtIndex:i];
            [ret replaceObjectAtIndex:i withObject:[AppUtils mutableContainer:obj]];
        }
        return ret;
    }
    else if ([container isKindOfClass:[NSMutableDictionary class]]) {
        NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithDictionary:container];
        for (NSString *k in [ret allKeys]) {
            [ret setValue:[AppUtils mutableContainer:[ret valueForKey:k]] forKey:k];
        }
        return ret;
    }
    return container;
}

+ (NSString *)sortRemindTime:(NSString *)remindTime
{
    if([AppUtils isEmpty:remindTime]){
        return remindTime;
    }
    remindTime = [remindTime stringByReplacingOccurrencesOfString:@":" withString:@"."];
    NSArray *array =  [remindTime componentsSeparatedByString:@","];
    array = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        if ([obj1 floatValue] > [obj2 floatValue]) {
            return NSOrderedDescending;
        }
        if ([obj1 floatValue] < [obj2 floatValue]) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
   return [[AppUtils joinArray:array] stringByReplacingOccurrencesOfString:@"." withString:@":"];;
}

+ (NSString *)getFileText:(NSString*)filename
{
    NSError *error;
    NSString *textFileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:filename ofType:@"txt"] encoding:NSUTF8StringEncoding error: & error];
    return textFileContents;
}

+ (NSDictionary *)getTextDrawAttribute:(CGFloat)fontSize color:(UIColor*)textColor
{
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    UIColor *shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    NSMutableParagraphStyle *paragraphStyle= [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowBlurRadius = 1.5;
    shadow.shadowColor = shadowColor;
   return @{NSFontAttributeName: font,NSParagraphStyleAttributeName:paragraphStyle,
                         NSForegroundColorAttributeName:textColor,NSShadowAttributeName:shadow,NSVerticalGlyphFormAttributeName:@0} ;
}

+ (void)setTextViewLineSpace:(UITextView *)textView space:(NSUInteger)lineSpace;
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:textView.font,
                                 NSForegroundColorAttributeName:textView.textColor,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
}

+ (void)setPickerViewStyle:(UIView *)view
{
    if(view.subviews != 0  )
    {
        if(view.bounds.size.height < 5)
        {
            view.backgroundColor = [UIColor clearColor];
        }
        
        [view.subviews enumerateObjectsUsingBlock:^( UIView *  obj, NSUInteger idx, BOOL *  stop) {
            [self setPickerViewStyle:obj];
        }];
    }
}

+(void)textViewScrollToBottom:(UITextView *)textView
{
    [textView scrollRangeToVisible:NSMakeRange(textView.text.length, 1)];
}
+(void)textViewScrollToTop:(UITextView *)textView
{
    BOOL flagSave = textView.scrollEnabled;
    if(flagSave){
        textView.scrollEnabled = NO;
        [AppUtils delay:^{
            textView.scrollEnabled = flagSave;
        }];
    }
}

+(NSArray *)joinArrayDict:(NSArray *)array WithKey:(NSString *)key
{
    if([AppUtils isEmptyArray:array]){
        return [NSArray array];
    }
    NSMutableArray *mutArr = [NSMutableArray array];
    for(NSDictionary *dict in array){
        NSString *value =[AppUtils toString:dict[key]];
        if([AppUtils isNotEmpty:value]){
            [mutArr addObject:value];
        }
    }
    return  mutArr;
}

/**
 * 将字符串的数组组装成字符创，指定符号隔开
 */
+(NSString *)joinArray:(NSArray *)array withSeparate:(NSString *)separateStr{
    NSString *result = @"";
    for(NSString *str in array){
        if([AppUtils isEmpty:result]){
            result = str;
        }else{
            result = [NSString stringWithFormat:@"%@%@%@",result,separateStr,str];
        }
    }
    return result;
}

+(NSString *)joinArray:(NSArray *)array
{
  return  [AppUtils joinArray:array withSeparate:@","];
}

+(NSString *)removeString:(NSString *)str fromString:(NSString *)string
{
    if([AppUtils isEmpty:str]){
        return string;
    }
    
    NSMutableArray *arr = [NSMutableArray arrayWithArray:[string componentsSeparatedByString:@","]];
    NSArray *removeStr = [str componentsSeparatedByString:@","];
    for(NSString *s in removeStr){
        [arr removeObject:s];
    }
    return  [AppUtils joinArray:arr];
}

+(NSString *)appendString:(NSString *)oldStr withString:(NSString *)appendStr
{
    NSString *result = oldStr;
    if([AppUtils isEmpty:appendStr]){
        return result;
    }
    if([AppUtils isEmpty:result]){
        result = appendStr;
    }else{
        result =[NSString stringWithFormat:@"%@,%@",result,appendStr];
    }
    return result;
}

+(NSArray *)removeDuplicateremoveArr:(NSArray *)array
{
    NSSet *set = [NSSet setWithArray:array];
    NSMutableArray *result= [NSMutableArray array];
    for(id obj in [set allObjects]){
        [result addObject:obj];
    }
    return result;
}

+ (CGSize)getTextSize:(NSString *)content font:(UIFont *)font maxSize:(CGSize)maxSize
{
    if(content==nil){
        return CGSizeZero;
    }
    if (!font) {
        font = [UIFont systemFontOfSize:17];
    }
    if (CGSizeEqualToSize(maxSize, CGSizeZero) == YES ) {
        maxSize = CGSizeMake(SCREEN_WIDTH,CONTENT_HEIGHT);
    }
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    NSRange allRange = [content rangeOfString:content];
    [attrStr addAttribute:NSFontAttributeName
                    value:font
                    range:allRange];
    [attrStr addAttribute:NSForegroundColorAttributeName
                    value:[UIColor blackColor]
                    range:allRange];
    
    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attrStr boundingRectWithSize:maxSize
                                        options:options
                                        context:nil];
    return rect.size;
}

+(CGSize)fontWithString:(NSString *)str fontSize:(CGFloat)font  maxSize:(CGSize )size{
    NSDictionary *dic=@{NSFontAttributeName:[UIFont systemFontOfSize:font]};
    
    CGRect rect= [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    return  rect.size;
}

+(CGSize)labelSizeWithString:(NSString *)str font:(UIFont *)font  maxSize:(CGSize )size
{
    if([AppUtils isEmpty:str]){
        return CGSizeZero;
    }
    CGSize s = size;
    if(CGSizeEqualToSize(s, CGSizeZero)){
        s = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, s.width, s.height)];
    l.lineBreakMode = NSLineBreakByCharWrapping;
    l.text = str;
    l.font = font;
    l.numberOfLines = 0;
    [l sizeToFit];
    return l.size;
}

+(void)showStatusBar:(BOOL)show needAnimation:(BOOL)needAnimation
{
    UIStatusBarAnimation ani = needAnimation?UIStatusBarAnimationFade:UIStatusBarAnimationNone;
    [[UIApplication sharedApplication]setStatusBarHidden:!show withAnimation:ani];
}


+ (UIBarButtonItem *)addBarButton:(UIViewController *)controller title:(NSString *)title action:(SEL)action position:(PositionType)position
{
    return [AppUtils addBarButton:controller title:title action:action position:position fontSize:16];
}

+ (UIBarButtonItem *)addBarButton:(UIViewController *)controller title:(NSString *)title action:(SEL)action position:(PositionType)position fontSize:(CGFloat)size
{
    CGSize titleSize = [AppUtils fontWithString:title fontSize:size maxSize:CGSizeMake(SCREEN_WIDTH, size + 5)];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, titleSize.width, 44)];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:size];
    [btn setTitleColor:[UIColor colorWithString:COLOR_436BCF] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithString:COLOR_A0B6ED] forState:UIControlStateHighlighted];
    [btn setTitleColor:[UIColor colorWithString:COLOR_A0B6ED] forState:UIControlStateDisabled];
    [btn addTarget:controller action:action forControlEvents:UIControlEventTouchUpInside];
    btn.enabled = YES;
    //上面代码是为了定制才这样变成的，下面注释的代码是不定制下通用的写法
//    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStyleBordered target:controller action:action];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
//    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:size], NSFontAttributeName, nil];
//    [barButton setTitleTextAttributes:attrs forState:UIControlStateNormal];
    if (position == PositionTypeLeft) {
        controller.navigationItem.leftBarButtonItem = barButton;
    } else {
        controller.navigationItem.rightBarButtonItem = barButton;
    }
    return barButton;
}

+ (UIBarButtonItem *)addBarButton:(UIViewController *)controller image:(UIImage*)image action:(SEL)action position:(PositionType)position
{
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:controller action:action];
    
    if (position == PositionTypeLeft) {
        controller.navigationItem.leftBarButtonItem = barButton;
    } else {
        controller.navigationItem.rightBarButtonItem = barButton;
    }
    return barButton;
}

+ (void)showErrorAlert:(NSString *)title
{
    if([AppUtils isEmpty:title]){
        title = @"服务器出错啦";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:nil delegate:[AppUtils getAppDelegate] cancelButtonTitle:@"确认" otherButtonTitles: nil];
    alert.tag = Tag_alert_request_msg;
    if(![ServerMng sharedServerMng].alertShowFlag){
        [ServerMng sharedServerMng].alertShowFlag = YES;
        [alert show];
    }
}

+ (void)showErrorAlertByKick
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"退出通知" message:@"您的账号在另一地点登录，您已经被迫退出。如果不是您本人操作，您的密码可能已经泄露，建议您重新登录修改密码。" delegate:[AppUtils getAppDelegate] cancelButtonTitle:@"取消" otherButtonTitles:@"重新登录",nil];
    alert.tag = Tag_alert_login_msg;
    if(![ServerMng sharedServerMng].alertShowFlag){
        [ServerMng sharedServerMng].alertShowFlag = YES;
        [alert show];
    }
}


+ (void)showErrorAlertToLogin:(NSString *)title needRequest:(BOOL)needRequest
{
    if([AppUtils isEmpty:title]){
        title = @"服务器出错啦";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:nil delegate:[AppUtils getAppDelegate] cancelButtonTitle:nil otherButtonTitles:@"确认",nil];
    alert.accessibilityValue = [AppUtils toStr:needRequest];
    alert.tag = Tag_alert_login_msg;
    if(![ServerMng sharedServerMng].alertShowFlag){
        [ServerMng sharedServerMng].alertShowFlag = YES;
        [alert show];
    }
}


+(void)setNavigationBarStyle
{
    UINavigationBar *navigationBar = [UINavigationBar appearance];
    UIImage *headBgImg = [UIColor imageWithColor:[UIColor colorWithString:COLOR_17A4FF] size:CGSizeMake(1.0, 1.0)];
    
    navigationBar.barStyle = UIBarStyleDefault;
    navigationBar.tintColor = [UIColor colorWithString:COLOR_FFFFFF];
    [navigationBar setBackgroundImage:headBgImg forBarMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[[UIImage alloc] init]];
    
    navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:18], NSFontAttributeName,[UIColor colorWithString:COLOR_FFFFFF],NSForegroundColorAttributeName,nil];
    
    UIImage *image = [[UIImage imageNamed:@"nav_back_white"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 50, 0, 1)];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:image forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    // 设置UIBarButtonItem透明
    [[UIBarButtonItem appearance] setBackgroundImage:[[UIImage alloc]init] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

    // 隐藏返回图标的文字
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, 0) forBarMetrics:UIBarMetricsDefault];
}

+(void)modifyNavigationBarStyle
{
    UINavigationBar *navigationBar = [UINavigationBar appearance];
    if([AppUtils isLogout]){
        UIImage *headBgImg = [UIColor imageWithColor:[UIColor colorWithString:COLOR_E8F0F6] size:CGSizeMake(1.0, 1.0)];
        navigationBar.tintColor = [UIColor colorWithString:COLOR_436BCF];
        [navigationBar setBackgroundImage:headBgImg forBarMetrics:UIBarMetricsDefault];
    }else{
        
        UIImage *headBgImg = [UIColor imageWithColor:[UIColor colorWithString:COLOR_FFFFFF] size:CGSizeMake(1.0, 1.0)];
        
        navigationBar.tintColor = [UIColor colorWithString:COLOR_436BCF];
        [navigationBar setBackgroundImage:headBgImg forBarMetrics:UIBarMetricsDefault];
    }
}

+ (UIImage*)grayImage:(UIImage*)image
{
    // Adapted from this thread: http://stackoverflow.com/questions/1298867/convert-image-to-grayscale
    const int RED = 1;
    const int GREEN = 2;
    const int BLUE = 3;
    
    // Create image rectangle with current image width/height
    CGRect imageRect = CGRectMake(0, 0, image.size.width * image.scale, image.size.height * image.scale);
    
    int width = imageRect.size.width;
    int height = imageRect.size.height;
    
    // the pixels will be painted to this array
    uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));
    
    // clear the pixels so any transparency is preserved
    memset(pixels, 0, width * height * sizeof(uint32_t));
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    // create a context with RGBA pixels
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
    
    // paint the bitmap to our context which will fill in the pixels array
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [image CGImage]);
    
    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x++) {
            uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
            
            // convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
            uint32_t gray = 0.2126 * rgbaPixel[RED] + 0.7152 * rgbaPixel[GREEN] + 0.0722 * rgbaPixel[BLUE];
            
            // set the pixels to gray
            rgbaPixel[RED] = gray;
            rgbaPixel[GREEN] = gray;
            rgbaPixel[BLUE] = gray;
        }
    }
    
    // create a new CGImageRef from our context with the modified pixels
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    
    // we're done with the context, color space, and pixels
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    free(pixels);
    
    // make a new UIImage to return
    UIImage *resultUIImage = [UIImage imageWithCGImage:imageRef
                                                 scale:image.scale
                                           orientation:UIImageOrientationUp];
    
    // we're done with image now too
    CGImageRelease(imageRef);
    
    return resultUIImage;
}

+ (void)setButtonShadowStyle:(UIButton *)btn
{
    if(btn.enabled){
        btn.layer.shadowColor = [UIColor colorWithString:COLOR_8AABFC].CGColor;
    }else{
        btn.layer.shadowColor = [UIColor colorWithString:COLOR_CEDAF6].CGColor;
    }
    btn.layer.shadowOffset = CGSizeMake(0, 5);
    btn.layer.shadowRadius = 10;
    btn.layer.shadowOpacity = 0.8;
}

+(void)checkAppUpdate
{
    [[UpgradeView sharedInstance] checkAppVersion];
}

+(NSString *)createRandomNumber
{
    return [NSString stringWithFormat:@"%04zi",[AppUtils randomInt:10000]];
}

+ (void)attachSuperController:(UIViewController *)superCtrl subCtrl:(UIViewController *)subCtrl superView:(UIView *)superView
{
    if (nil == superCtrl || nil == subCtrl || nil == superView) {
        return;
    }
    [superCtrl addChildViewController:subCtrl];
    [superView addSubview:subCtrl.view];
    [subCtrl.view setFrame:CGRectMake(0, 0, superView.frame.size.width, superView.frame.size.height)];
}

+ (void)clearSubView:(UIView *)view
{
    if(view){
        for(UIView *v in view.subviews){
            [v removeFromSuperview];
        }
    }
}


+ (void)setImage:(UIImageView *)imageView url:(NSString*)url
{
    [AppUtils setImage:imageView url:url cutSize:NO];
}

+ (void )setImage:(UIImageView *)imageView url:(NSString*)url cutSize:(BOOL)cutCenterImage
{
    [AppUtils setImage:imageView url:url placeholder:@"default_image_icon"];
}

+ (void)setImage:(UIImageView *)imageView url:(NSString*)url placeholder:(NSString*)defaultImgName
{
    if ([AppUtils isEmpty:url]) {
        if (![AppUtils isEmpty:defaultImgName]) {
            [imageView setImage:[UIImage imageNamed:defaultImgName]];
        }
        else {
            [imageView setImage:nil];
        }
        return;
    }
    UIImage *retImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:url];
    if (nil != retImage) {
        [imageView setImage:retImage];
        return;
    }
    
    [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:defaultImgName] options:SDWebImageDelayPlaceholder];
}

/**
 *获取对应水质等级的颜色
 */
+ (UIColor *)getQualityClass:(NSString *)waterQualityClassName
{
    NSString *color= COLOR_4DD04D; //COLOR_17A4FF;
    //    if([WATER_LEVEL2 isEqualToString:waterQualityClassName]){
    //        color= COLOR_0082DC;
    //    }else if([WATER_LEVEL3 isEqualToString:waterQualityClassName]){
    //        color= COLOR_4DD04D;
    //    }else if([WATER_LEVEL4 isEqualToString:waterQualityClassName]){
    //        color= COLOR_2A9C2A;
    //    }else if([WATER_LEVEL5 isEqualToString:waterQualityClassName]){
    //        color= COLOR_F3A723;
    //    }else
    if([WATER_LEVEL5_BAD isEqualToString:waterQualityClassName] ||[@"06" isEqualToString:waterQualityClassName]){
        color= COLOR_FD6766;
    }
    return [UIColor colorWithString:color];
}

+(NSString *)getQualityClassName:(NSString *)waterQualityClassName
{
    NSString *result = WATER_LEVEL5;
    if([@"06" isEqualToString:waterQualityClassName]){
        result = WATER_LEVEL5_BAD;
    }
    return result;
}


/**
 *一点一策的view创建
 */
+ (UIView *)addReasonView:(CGRect)frame title:(NSString *)title reasonLabel:(NSString *)reasonLabel resonDetail:(NSString *)detail showDetail:(BOOL)showDetail target:(id)target selector:(SEL)sel
{
    if([AppUtils isEmpty:title] && [AppUtils isEmpty:reasonLabel]){
        return nil;
    }
    
    UIView *outView  = [[UIView alloc] initWithFrame:frame];
    outView.backgroundColor = [UIColor clearColor];
    UIColor *textColor = [UIColor colorWithString:COLOR_989AA6];
    UIFont *textFont = [UIFont systemFontOfSize:13];
    if([AppUtils isNotEmpty:title]){
        outView.backgroundColor = [UIColor colorWithString:COLOR_EDEEEF];
        UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 20)];
        l.text = [NSString stringWithFormat:@"  %@",title];
        l.font = textFont;
        l.textColor = textColor;
        [outView addSubview:l];
    }
    if([AppUtils isNotEmpty:reasonLabel]){
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, outView.width-80-50, 20)];
        label2.textColor = textColor;
        label2.text = reasonLabel;
        label2.font = textFont;
        [outView addSubview:label2];
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(outView.width-50, 0, 20, 20)];
        icon.image = [UIImage imageNamed:@"pull_donw_icon"];
        icon.contentMode = UIViewContentModeCenter;
        icon.userInteractionEnabled = YES;
        [icon addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:target action:sel]];
        [outView addSubview:icon];
        outView.height = 20;
        
        if(showDetail){
            UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(80, 25, outView.width-80-50, 0)];
            label3.backgroundColor = [UIColor clearColor];
            label3.font = textFont;
            label3.textColor = [UIColor colorWithString:COLOR_494B55];
            label3.text = detail;
            label3.textAlignment = NSTextAlignmentLeft;
            label3.numberOfLines = 0;
            CGFloat label3H =[AppUtils labelSizeWithString:detail font:textFont maxSize:CGSizeMake(label3.width, SCREEN_HEIGHT)].height;
            label3.height = label3H;
            [outView addSubview:label3];
            outView.height += (label3H>0?10:0) + label3H;
            icon.transform = CGAffineTransformRotate(icon.transform,M_PI);
            return outView;
        }
    }else{
        outView.height = 20;
    }
    return outView;
}

+ (NSString *)getScoutStatusStr:(ScoutStatus)scoutStatus
{   //巡查状态 0,1,2等待整改 整改中 整改完成
    NSString *str = nil;
    switch (scoutStatus) {
        case ScoutStatusWait:
            str = @"等待整改";
            break;
        case ScoutStatusDoning:
            str = @"整改中";
            break;
        case ScoutStatusFinish:
            str = @"整改完成";
            break;
        default:
            break;
    }
    return str;
}


+ (void)openImagePicker:(id)controller sourceType:(UIImagePickerControllerSourceType)sourceType allowsEditing:(BOOL)allowsEditing ratio:(CGFloat)ratio
{
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [Toast makeText:@"该设备不支持"];
        return;
    }
    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
    [imgPicker setSourceType:sourceType];
    [imgPicker setDelegate:controller];
    [imgPicker setAllowsEditing:NO];
    if ([controller isKindOfClass:[ImagePickerViewController class]]) {
        [controller setImagePickerEditing:allowsEditing ratio:ratio parent:imgPicker];
    }
    [controller presentViewController:imgPicker animated:YES completion:^{}];
}


+ (UIImage *)fixImageOrientation:(UIImage *)image
{
    // No-op if the orientation is already correct
    if (image.imageOrientation == UIImageOrientationUp)
        return image;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage), 0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

+ (UIImage *)compressImageQualityToImage:(UIImage *)image
{
    if(image==nil){
        return image;
    }
    CGFloat compression = 0.7;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    DSLog(@"source image size:%.2fkb", imageData.length / 1024.0);
    while (imageData.length > IMAGE_MAX_SIZE && compression > 0.1) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    DSLog(@"final image size:%.2fkb", imageData.length / 1024.0);
    return [UIImage imageWithData:imageData];
}

+(NSUInteger)getFileTypeIndex:(NSString *)fileExtName
{
    NSUInteger value = 100;
    NSArray *arr = @[@"png",@"jpg",@"jpeg",@"bmp",@"txt",@"pdf",@"doc",@"docx",@"xls",@"xlsx",@"ppt",@"pptx"];
    if([AppUtils isNotEmpty:fileExtName] && [arr containsObject:fileExtName]){
        value = [arr indexOfObject:fileExtName];
    }
    return value;
}


@end
